<?php
class Reg extends BZ_Controller
{
    public function _init()
    {
        $this->load->library(array('encrypt', 'sms/sms', 'alidayu/alidayusms'));
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('getpwd_phone_model', 'getpwd_phone');
    }

    public function index()
    {
        if ($this->frontUser) {
            $this->redirect(site_url('tourism/tourismprovider/grid'));
        }
        $username = $this->input->get('username');
        if (!empty($username)) {
            $data['parent_name'] = $username;
        } else {
            $data['parent_name'] = get_cookie('true_user');
        }
        $this->load->view('login/register/index', $data);
    }

    /**
     * 注册提交页面
     */
    public function toRegister()
    {
        $userName = $this->input->post('username');
        $endTime  = date('Y-m-d H:i:s');
        $postData = $this->input->post();
        $postData['mobile_phone'] = $userName;
        if (!valid_mobile($userName)) {
            $this->ajaxJson(false, '手机号码格式有误');
        }
        if ($this->input->post('password') != $postData['confirmPassword']) {
            $this->ajaxJson(false, '2次输入的密码不一致');
        }
        $result = $this->user->validateName($postData['username']);
        if ($result->num_rows() > 0) {
            $this->ajaxJson(false, '手机号码已经注册');
        }
        $verify = $this->user_code->findOne(['mobile' => $userName, 'code' => $postData['verify']], 'id, end_time');//, 'end_time' => $endTime
        if ($verify->num_rows() <= 0) {
            $this->ajaxJson(false, '手机验证码错误~');
        }
        if ($verify->row(0)->end_time < $endTime) {
            $this->ajaxJson(false, '手机验证码超过有效期，请重新获取~');
        }

        if (!empty($postData['parent_name'])) {
            $parent = $this->user->validateName($postData['parent_name']);
            if ($parent->num_rows() > 0) {
                $parent_id = $parent->row()->uid;
            } else {
                $this->jsonMessage('推荐人不存在');
            }
        } else {
            $parent_id = UTID_BEIZHU;
        }
        $this->db->trans_begin();
        $userId = $this->user->insertUser($postData, $parent_id);
        $userAccountId = $this->user_account->insertUserAccount($postData, $userId, $parent_id);
        if (!$userId || !$userAccountId || $this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $this->ajaxJson(false, '网络繁忙，服务器忙，请稍候再试');
        } else {
            $this->db->trans_commit();
        }

        $userType = $this->usertype(UTID_CUSTOMER);
        $session = array(
            'ACT_UID'        => $userId,
            'ACT_UTID'       => UTID_CUSTOMER,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => 0,
            'ALIAS_NAME'     => urlencode($userName),
            'OWNER_ID'       => $userId,
            'OWNER_NAME'     => $userName,
            'PARENT_ID'      => $parent_id,
            'PERSONAL_PHOTO' => urlencode($user->personal_photo),
        );
        set_cookie('frontUser', serialize($session), 3 * 24 * 3600);
        $this->cache->memcached->save('frontUser', serialize($session), 3 * 24 * 3600);
        $backUrl = $this->input->post('backurl') ? urldecode($this->input->post('backurl')) : site_url('tourism/tourismprovider/grid');

        $this->ajaxJson(true, $backUrl);
    }

    /**
     * 验证用户是否注册过。
     */
    public function checkPhone()
    {
        $phone = $this->input->post('username');
        if (!valid_mobile($phone)) {
            $this->ajaxJson(false, '手机号码格式有误');
        }
        $result = $this->user->validateName($phone);
        if ($result->num_rows() > 0) {
            $this->ajaxJson(false, '该手机号码已注册');
        }

        return $this->sendCommonSms($phone, 'SMS_135430022');
    }
}